package middleware

import (
	"fitness/go-admin/pkg/logger"
	"time"

	"github.com/gin-gonic/gin"
)

// QueryPerformance 查询性能统计
type QueryPerformance struct {
	QueryCount    int
	TotalDuration time.Duration
	SlowQueries   int
}

// QueryMonitor 查询性能监控中间件（简化版）
// 注意：完整的SQL监控需要在GORM层实现，这里只做请求级别的统计
func QueryMonitor() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 记录请求开始时间
		start := time.Now()

		// 在上下文中初始化性能统计
		perf := &QueryPerformance{}
		c.Set("query_performance", perf)

		// 继续处理请求
		c.Next()

		// 请求处理完成后记录统计
		duration := time.Since(start)

		// 记录请求总耗时
		logger.Debug("请求处理完成",
			"method", c.Request.Method,
			"path", c.Request.URL.Path,
			"status", c.Writer.Status(),
			"duration", duration.String(),
		)

		// 如果请求耗时超过1秒，记录警告
		if duration > time.Second {
			logger.Warn("慢请求检测",
				"method", c.Request.Method,
				"path", c.Request.URL.Path,
				"duration", duration.String(),
			)
		}
	}
}

// RecordQuery 记录单个查询（在Repository中调用）
func RecordQuery(c *gin.Context, duration time.Duration) {
	if c == nil {
		return
	}

	perfVal, exists := c.Get("query_performance")
	if !exists {
		return
	}

	perf, ok := perfVal.(*QueryPerformance)
	if !ok {
		return
	}

	perf.QueryCount++
	perf.TotalDuration += duration

	// 超过200ms认为是慢查询
	if duration > 200*time.Millisecond {
		perf.SlowQueries++
	}
}
